package csc.traning.wpsj.servlet.upload;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.traning.wpsj.dao.User;

/**
 * Servlet implementation class FileDeleteServlet
 */
public class FileDeleteServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileDeleteServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String navPage = "";
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			throw new ServletException("Required to login");
		}

		
		
		String userPath = "users/" + user.getUserName() + "/file_uploaded";
		String realUserPath = getServletContext().getRealPath(userPath);
		String currentDir = (String) session.getAttribute("currentDir");
		String[] selectFile = request.getParameterValues("fileSelect");
			if (selectFile == null || selectFile.length < 1) {
				navPage = "file-management";
			} else {
				for (int i = 0; i < selectFile.length; i++) {
					
					String realPath = realUserPath + selectFile[i];
					File filedelete = new File(realPath);
					deleteFolder(filedelete);
					try {

						filedelete.delete();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				navPage = "file-management";
			}

		
		request.setAttribute("forwardDir", currentDir);
		RequestDispatcher dispatcher = request.getRequestDispatcher(navPage);
		dispatcher.forward(request, response);
	}

	public static void deleteFolder(File folder) {
		File[] files = folder.listFiles();
		if (files != null) { // some JVMs return null for empty dirs
			for (File f : files) {
				if (f.isDirectory()) {
					deleteFolder(f);
				} else {
					f.delete();
				}
			}
		}
		folder.delete();
	}
}
